package com.vueblog.webapi.controller.admin;


import com.vueblog.webapi.controller.BaseController;
import com.vueblog.webapi.entity.UserEntity;
import com.vueblog.webapi.request.LoginRequest;
import com.vueblog.webapi.response.BasePageResponse;
import com.vueblog.webapi.response.BaseResponse;
import com.vueblog.webapi.service.IUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Enumeration;

/**
 * luosj
 */
@Controller
@RequestMapping("/admin")
@CrossOrigin
public class LoginController extends BaseController {


    @Autowired
    private IUserService userService;

    /**
     * 登录页面
     * @return
     */
    @GetMapping("/loginto")
    public String loginPage() {
        return "admin/login";
    }

    /**
     * 登录
     */
    @PostMapping ("/login")
    @ResponseBody
    public BaseResponse login(@RequestBody LoginRequest loginRequest, HttpServletRequest request, HttpServletResponse response, BindingResult bindingResult) {
        // 校验输入格式是否正确
        checkBindingResult(bindingResult);
        // 获取当前的用户
        Subject subject = SecurityUtils.getSubject();
        // 封装用户的登录数据
        UsernamePasswordToken token = new UsernamePasswordToken(
                loginRequest.getUsername(), loginRequest.getPassword());
        try {
            subject.login(token); // 执行登录方法，如果没有异常就说明OK
        } catch (UnknownAccountException e) {
            return new BaseResponse(-1,"用户名不存在");
        } catch (IncorrectCredentialsException e) {
            return new BaseResponse(-1,"密码错误");
        } catch (Exception e) {
            return new BaseResponse(-1,"登录出错");
        }
        // 登录成功之后,在shrio的session中放入 user对象
        Session session = subject.getSession();
        UserEntity user =(UserEntity) subject.getPrincipal();
        user.setPassword(null);
        session.setAttribute("user", user);

//        Enumeration<String> headerNames = request.getHeaderNames();


        // 如下为给访客端提供的代码
//        Cookie[] cookies = request.getCookies();
//        for (Cookie cookie : cookies) {
//            if ("JSESSIONID".equals(cookie.getName())) {
//                // 将用户登录的JSESSIONID放在上下文对象中
//                request.getServletContext().setAttribute("loginCookie", cookie.getValue());
//                Cookie cookie2 = new Cookie("loginCookie", cookie.getValue());
//                response.addCookie(cookie2);
//            }
//        }

        userService.setIsOnLine(true);// 用户登录状态设置为true
        return new BaseResponse(0,"登录成功");
    }

    /**
     * 后台管理主页面
     * @return
     */
    @GetMapping("/index")
    public String adminIndexPage() {
        return "admin/index";
    }

    /**
     * 注销
     * @return
     */
    @GetMapping("/logout")
    public String logout() {
        // 用户登录状态设置为false
        userService.setIsOnLine(false);
        // 如下只能针对一次会话（即同源的同步请求或异步请求）
        // 获取当前“用户”
        Subject subject = SecurityUtils.getSubject();
        // 获取session
        Session session = subject.getSession();
        // 清除session缓存
        session.stop();
        // 注销
        subject.logout();
        // 重定向到登录页面
        return "redirect:/admin/login.html";
    }
}
